package com.xiaoyu.izf.service;

import com.xiaoyu.izf.model.GoodsInfo;
import com.xiaoyu.izf.model.GoodsOrder;
import com.xiaoyu.izf.model.UserInfo;
import com.xiaoyu.izf.repository.GoodsInfoDao;
import com.xiaoyu.izf.repository.GoodsOrderDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

@Service
public class GoodsOrderService extends BaseService{
    @Autowired
    private GoodsOrderDao goodsOrderDao;
    @Autowired
    private GoodsInfoDao goodsInfoDao;

    public GoodsOrder orderAdd(String orderId, UserInfo user, GoodsInfo goods, int buyNum){
        GoodsOrder order = new GoodsOrder();
        order.setId(orderId);
        order.setOutTradeNo("");
        order.setGoodsId(goods.getId());
        order.setUid(user.getId());
        order.setTotalAmount(goods.getPrice()*buyNum);
        order.setOrderPrice(goods.getPrice());
        order.setBuyNum(buyNum);
        order.setOpenId("");
        order.setChannel("alipay");
        order.setOrderStatus(0);
        order.setInsertTime(new Timestamp(System.currentTimeMillis()));
        order.setPayTime(new Timestamp(System.currentTimeMillis()));
        order.setReturnTime(new Timestamp(System.currentTimeMillis()));
        order.setIsTest(user.getIsTest());
        return  goodsOrderDao.save(order);
    }

    public Page<GoodsOrder> listForApi(int p, int psize, int uid){
        PageRequest pageRequest = buildPageRequest(p, psize, "insertTime");
        Page<GoodsOrder> page = goodsOrderDao.findAll(new Specification<GoodsOrder>() {
            @Override
            public Predicate toPredicate(Root<GoodsOrder> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<Predicate>();
                list.add(cb.equal(root.get("uid").as(Integer.class),uid));
                Predicate[] p = new Predicate[list.size()];
                query.where(cb.and(list.toArray(p)));
                return query.getRestriction();
            }
        }, pageRequest);
        return  page;
    }

    public GoodsOrder orderOne(String orderId){
        return goodsOrderDao.findOneById(orderId);
    }

    public GoodsOrder orderSave(GoodsOrder order){
        return goodsOrderDao.save(order);
    }

    public void goodsSaleNumAdd(int goodsId,int saleNum){
        GoodsInfo goods = goodsInfoDao.findOneById(goodsId);
        if(goods!=null){
            goods.setSaleNum(goods.getSaleNum()+saleNum);
            goodsInfoDao.save(goods);
        }
    }
}
